<?php

namespace app\api\controller;

use app\admin\model\product\Attr;
use app\admin\model\product\Attrs;
use app\admin\model\product\Listo;
use app\admin\model\product\Lists;
use app\admin\model\product\Order;
use app\admin\model\product\Value;
use app\common\controller\Api;
use think\Db;
use think\Exception;
use think\Request;


class Userlists extends Api
{
    private static $model;
    protected $noNeedLogin = [''];
    protected $noNeedRight = '*';


    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        self::$model = new \app\admin\model\user\Lists();
    }

    /**
     * 显示资源列表
     * @throws \think\exception\DbException
     */
    public function lists()
    {
        $pageSize = input('page_size', 15);
        $categoryId = input('category_id');
        if (!$categoryId) {
            $this->error('参数缺失！');
        }
        $where = [
            'status' => 'normal',
            'category_id' => $categoryId,
        ];

        $keyword = trim(input('keyword'));
        if ($keyword) {
            $where['name'] = ['like', '%' . $keyword . '%'];
        }

        $list = self::$model->field('id,name,image,intro,detail,stock')->where($where)->order('id desc')->paginate($pageSize)->each(function ($item) {
            $item['image'] = make_full_url($item['image']);
        });

        $this->success('物资列表', $list);
    }

    /**
     * 商品详情
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function read()
    {
        $id = $this->request->get('id');
        if (!$id) {
            $this->error('参数缺失！');
        }

        $row = self::$model->field('id,name,sid,image,intro,goods_detail,original_price,member_price,sell_num,goods_num,pics')->find($id);
        if (!$row) {
            $this->error('该商品不存在！');
        }

        $row['image'] = make_full_url($row['image']);

        $pics = explode(',', $row['pics']);

        foreach ($pics as &$val) {
            $val = make_full_url($val);
        }

        $row['pics'] = $pics;

        $attrs = Attrs::where('product_id', $id)->select();
        $attrs_arr = [];
        if ($attrs) {
            foreach ($attrs as $v) {
                $name = Attr::where('id', $v['attr_id'])->value('name');
                $value_ids_arr = explode(',', $v['value_ids']);
                $sons = [];
                foreach ($value_ids_arr as $v1) {
                    $vname = Value::where('id', $v1)->value('name');
                    $sons[] = [
                        'id' => $v1,
                        'name' => $vname
                    ];
                }
                $item = [
                    'id' => $v['attr_id'],
                    'name' => $name,
                    'sons' => $sons
                ];
                $attrs_arr[] = $item;
            }
        }

        $row->attrs = $attrs_arr;
        $this->success('商品详情', $row);
    }

    /**
     * 社区入库
     */
    public function create()
    {
//        $name = $this->request->post('name');
//        $image = $this->request->post('image');
        $listo_id = $this->request->post('id');
        $category_id = $this->request->post('category_id');
        $total = $this->request->post('total');
        $reply_image = $this->request->post('reply_image');
        $remark = $this->request->post('remark');
        $type = $this->request->post('type');
        $file_path = $this->request->post('file_path');
        if (!$listo_id || !$category_id || !$total || !$reply_image || !$remark) {
            $this->error('物资信息，数量，入库说明，签名缺一不可');
        }

        $row = Listo::find($listo_id);
        if (!$row) {
            $this->error('该申请单不存在！');
        }

        if ($row->status != 20) {
            $this->error('该申请单不可入库！');
        }

        Db::startTrans();
        try {

            $user_id = $this->auth->id;
            $user = $this->auth->getUser();
            $product_id = $row->product_id;
            $pinfo = Lists::find($product_id);
            $data = [
                'user_id' => $user_id,
                'name' => $pinfo->name,
                'image' => $pinfo->image,
                'category_id' => $category_id,
                'product_id' => $product_id,
                'listo_id' => $listo_id,
                'total' => $total,
                'reply_image' => $reply_image,
                'remark' => $remark,
                'file_path' => $file_path,
                'status' => 1
            ];

            $ret = \app\admin\model\User\Regist::create($data);

            $community_id = $user->community_id;
            $urow = \app\admin\model\user\Lists::where('product_id', $product_id)
                ->where('category_id', $category_id)
                ->where('community_id', $community_id)
                ->find();

            if (!$urow) {
                $ldata = [
                    'name' => $pinfo->name,
                    'image' => $pinfo->image,
                    'category_id' => $category_id,
                    'product_id' => $product_id,
                    'community_id' => $community_id,
                    'total' => $total,
                    'stock' => $total,
                    'type' => $type,
                ];

                \app\admin\model\user\Lists::create($ldata);
            } else {
                $urow->total += $total;
                $urow->stock += $total;
                $ret = $urow->save();
            }

            $row->status = 25;
            $row->save();

            $num = Listo::where('order_id', $row->order_id)->where('status', '<', 25)->count();
            if ($num <= 0) {
                Order::where('id', $row->order_id)->setField('status', 25);
            }

            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }


        $this->success('入库成功');
    }
}
